package net.wicp.tams.commons.web.http;

import java.util.concurrent.FutureTask;

import org.apache.commons.lang.ArrayUtils;
import org.apache.http.Header;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpRequestBase;
import org.apache.http.entity.StringEntity;
import org.apache.http.message.BasicHeader;
import org.apache.http.protocol.HTTP;
import org.apache.tapestry5.json.JSONObject;

public abstract class HttpClient {

	public static final String ENCODE = "UTF-8";
	public static final String HEAD_TYPE = "application/json";
	public static final String CONTENT_TYPE = "text/json";

	public static HttpResult doGet(String url) {
		HttpRequestBase rq = new HttpGet(url);
		HttpThread ht = new HttpThread(rq);
		HttpResult result = ht.call();
		return result;
	}

	public static FutureTask<HttpResult> doGetAsyn(String url) {
		HttpRequestBase rq = new HttpGet(url);
		HttpThread ht = new HttpThread(rq);
		return ht.callAsyn();
	}

	public static HttpResult doPost(String url, JSONObject param, Header... headers) {
		HttpThread ht = doPostCommon(url, param.toString(true), headers);
		HttpResult result = ht.call();
		return result;
	}

	public static HttpResult doPost(String url, Object... params) {
		JSONObject param = new JSONObject(params);
		return doPost(url, param);
	}

	public static FutureTask<HttpResult> doPostAsyn(String url, JSONObject param, Header... headers) {
		HttpThread ht = doPostCommon(url, param.toString(true), headers);
		return ht.callAsyn();
	}

	public static FutureTask<HttpResult> doPostAsyn(String url, Object[] params, Header... headers) {
		JSONObject param = new JSONObject(params);
		return doPostAsyn(url, param, headers);
	}

	public static HttpThread doPostCommon(String url, String param, Header... headers) {
		HttpPost rq = new HttpPost(url);
		rq.addHeader(HTTP.CONTENT_TYPE, HEAD_TYPE);
		if (ArrayUtils.isNotEmpty(headers)) {
			for (Header header : headers) {
				rq.addHeader(header);
			}
		}
		StringEntity se = new StringEntity(param, ENCODE);
		se.setContentType(CONTENT_TYPE);
		se.setContentEncoding(new BasicHeader(HTTP.CONTENT_TYPE, HEAD_TYPE));
		rq.setEntity(se);
		HttpThread ht = new HttpThread(rq);
		return ht;
	}

}
